# -*- coding: utf-8 -*-
# @Author  : qiangjun.chen
# @Date    : 2024/4/27 13:49
import re
import sys

import requests  # pip3 install pymysql
import pymysql  # pip3 install pymysql
from six import itervalues  # pip3 install six -i https://pypi.tuna.tsinghua.edu.cn/simple/
import pymysql
from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler  # pip install --upgrade spark_ai_python
from sparkai.core.messages import ChatMessage

# 星火认知大模型v3.5的URL值，其他版本大模型URL值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
SPARKAI_URL = 'wss://spark-api.xf-yun.com/v3.5/chat'
# 星火认知大模型调用秘钥信息，请前往讯飞开放平台控制台（https://console.xfyun.cn/services/bm35）查看  -- 可以替换自己的
SPARKAI_APP_ID = '054048dc'
SPARKAI_API_SECRET = 'MzU4NmE0MjhlMmY2YTBmZTc2YzY4NWQy'
SPARKAI_API_KEY = '250178de81b1a34a00dc4b3f727420e3'
# 星火认知大模型v3.5的domain值，其他版本大模型domain值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
SPARKAI_DOMAIN = 'generalv3.5'
# 数据库配置
DBConfig = {
    "host": "127.0.0.1",
    "port": 3306,
    "user": "root",
    "password": "123456",
    "db": "mytest",
    "charset": "utf8mb4"
}

'''
你之后的回答会严格按照以下格式回复：
早上：
食材：xxx、xxx、xxx。
做法：xxx；xxx；xxx。
能量：xxx大卡。
中午：
食材：xxx、xxx、xxx。
做法：xxx；xxx；xxx。
能量：xxx大卡。
晚上：
食材：xxx、xxx、xxx。
做法：xxx；xxx；xxx。
能量：xxx大卡。
'''

con = '''
    我是三高患者；我现在是肥胖体型；我不想吃生姜；我想要减肥；给我定制一份早中晚餐的食谱，总体能量在2000大卡，请严格按照下列格式给出方案：
    早上：
     食材：XXX。
     做法：XXX。
     能量：XXX。
            '''

food_pattern = r'(.*?)(?:总?(热|能)量(分|搭)?配?)'
make_pattern = r'做法(?:：|\:)(.*?)$'
energy_pattern = r'(?:总?(热|能)量(分|搭)?配?)(?:：|\:)(.*?)做法'


def escape(string):
    return '`%s`' % string


def insert_update_data_mysql(tablename, **value):
    connect = pymysql.Connect(**DBConfig)
    try:
        _key_values = ", ".join(["%s = %s" % (escape(k), "%s") for k in value])
        sql_query = "INSERT INTO %s SET %s ON DUPLICATE KEY UPDATE %s" % (tablename, _key_values, _key_values)
        with connect.cursor() as cur:
            cur.execute(sql_query, list(itervalues(value)) * 2)
        return cur
    except Exception as e:
        raise Exception("调用mysql插入方法时发生错误：{}".format(e))
    finally:
        connect.commit()
        connect.close()


def format_content(text):
    if text is None or text == '':
        return ''
    for i in range(len(text), 0, -1):
        if text[i - 1] == '。':
            result = text[:i]
            if result is not None or result != '':
                return result
            else:
                return ''
    return text


def build_content(text):
    if text is None or text == '':
        return ''
    energy_reg = re.compile(r'(总?(热|能)量(分|搭)?配?)')
    make_reg = re.compile(r'((做|作|方)法)')
    match_energy = energy_reg.search(text)
    match_make = make_reg.search(text)
    if match_energy:
        energy = match_energy.group(1)
        return text.replace(energy, '\n' + energy)
    if match_make:
        make = match_make.group(1)
        return text.replace(make, '\n' + make)
    return text


def get_menu(matched):
    if matched is None:
        return {
            'full': '',
            'food': '',
            'make': '',
            'energy': ''
        }
    match_content = matched.group(1)
    if match_content != '' and match_content:
        match_content = match_content.replace('：', ':')
    full_content = build_content(match_content)
    food_content = ''
    make_content = ''
    energy_content = ''
    # print(match_content)
    # print('---------------')
    food = re.search(food_pattern, match_content)
    make = re.search(make_pattern, match_content)
    energy = re.search(energy_pattern, match_content)
    if food:
        food_content = format_content(food.group(1))
    if make:
        make_content = format_content(make.group(1))
    if energy:
        energy_content = format_content(energy.group(1))

    return {
        'full': full_content,
        'food': food_content,
        'make': make_content,
        'energy': energy_content
    }


def start_chat(content=""):
    if not content:
        # print('error')
        return
    spark = ChatSparkLLM(
        spark_api_url=SPARKAI_URL,
        spark_app_id=SPARKAI_APP_ID,
        spark_api_key=SPARKAI_API_KEY,
        spark_api_secret=SPARKAI_API_SECRET,
        spark_llm_domain=SPARKAI_DOMAIN,
        streaming=False,
    )
    messages = [ChatMessage(
        role="user",
        content=content
    )]
    handler = ChunkPrintHandler()
    return spark.generate([messages], callbacks=[handler])


def main(condition):
    result = start_chat(condition)
    result = str(result)
    data = {
        'raw_data': result
    }
    insert_update_data_mysql('chat_data', **data)
    # result = str(result)
    # print('raw---' + result)
    #     result = '''
    # generations=[[ChatGeneration(text='早餐：\n\n- 燕麦粥(50克燕麦片，200毫升脱脂牛奶，1个水煮蛋)\n\n- 一份水果沙拉(苹果、香蕉、蓝莓、草莓等任选两种)\n\n- 一杯无糖豆浆或绿茶\n\n能量：约350大卡\n\n午餐：\n\n- 鸡胸肉沙拉(生菜、番茄、黄瓜、鸡胸肉丝、油醋汁)\n\n- 糙米饭(100克糙米，1.5升水)\n\n- 一份烤蔬菜(南瓜、胡萝卜、洋葱等任选两种)\n\n- 一杯低脂酸奶或柠檬水\n\n能量：约450大卡\n\n晚餐：\n\n- 红烧鱼块(鲈鱼或鳕鱼，姜片、葱段、料酒、酱油、糖)\n\n- 炒青菜(菠菜、油菜等任选一种，蒜末、盐)\n\n- 一碗紫薯粥(紫薯100克，水煮至熟烂)\n\n- 一杯温水或枸杞茶\n\n能量：约400大卡', message=AIMessage(content='早餐：\n\n- 燕麦粥(50克燕麦片，200毫升脱脂牛奶，1个水煮蛋)\n\n- 一份水果沙拉(苹果、香蕉、蓝莓、草莓等任选两种)\n\n- 一杯无糖豆浆或绿茶\n\n能量：约350大卡\n\n午餐：\n\n- 鸡胸肉沙拉(生菜、番茄、黄瓜、鸡胸肉丝、油醋汁)\n\n- 糙米饭(100克糙米，1.5升水)\n\n- 一份烤蔬菜(南瓜、胡萝卜、洋葱等任选两种)\n\n- 一杯低脂酸奶或柠檬水\n\n能量：约450大卡\n\n晚餐：\n\n- 红烧鱼块(鲈鱼或鳕鱼，姜片、葱段、料酒、酱油、糖)\n\n- 炒青菜(菠菜、油菜等任选一种，蒜末、盐)\n\n- 一碗紫薯粥(紫薯100克，水煮至熟烂)\n\n- 一杯温水或枸杞茶\n\n能量：约400大卡'))]] llm_output={'token_usage': {'question_tokens': 127, 'prompt_tokens': 127, 'completion_tokens': 246, 'total_tokens': 373}} run=[RunInfo(run_id=UUID('77916623-e6de-48bb-8744-b0d1a18e2a1a'))]
    #     '''
    result = result.replace('\n', '').replace('\\n', '').replace('*', '').replace('-', '').replace(' ', '')
    # print(result)
    pattern = r'ChatGeneration\(text=\'(.*?)\',message='

    # 使用re.search来查找匹配项
    match = re.search(pattern, result)
    breakfast_content = {}
    lunch_content = {}
    dinner_content = {}
    # 如果找到了匹配项，则打印它
    if match:
        content = match.group(1)
        breakfast_pattern = r'早(?:餐|饭)(?:：|\:)(.*?)(?:午|中)(?:餐|饭)'
        lunch_pattern = r'(?:午|中)(?:餐|饭)(?:：|\:)(.*?)晚(?:餐|饭)'
        dinner_pattern = r'晚(?:餐|饭)(?:：|\:)(.*?)$'
        breakfast = re.search(breakfast_pattern, content)
        lunch = re.search(lunch_pattern, content)
        dinner = re.search(dinner_pattern, content)

        breakfast_content = get_menu(breakfast)
        # print('breakfast-------' + str(breakfast_content))
        lunch_content = get_menu(lunch)
        # print('lunch-------' + str(lunch_content))
        dinner_content = get_menu(dinner)
        # print('dinner-------' + str(dinner_content))

    menu = {
        'breakfast': breakfast_content,
        'lunch': lunch_content,
        'dinner': dinner_content
    }
#     print(menu)


arg1 = sys.argv[1]
result = start_chat(arg1)
print(result)

# if __name__ == '__main__':
#     main()
